<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="模板号"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找模板
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加模板
      </el-button>

      <!-- 添加模板 -->
      <el-dialog
        v-if="dialogStatus!=='check'"
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
        <el-form :rules="carModelRules" :model="carModel" style="max-height:550px;overflow-y:auto;">
          <el-form-item label="模板名" prop="name">
            <el-input v-model="carModel.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="模板描述">
            <el-input
              v-model="carModel.description"
              type="textarea"
              :rows="3"
              placeholder="此处填写模板描述"
            />
          </el-form-item>

          <!-- 测试项模板实例 -->
          <el-form-item style="margin-bottom:0px" label="测试项模板实例" prop="tableOptions.name" />
          <el-form-item v-for="(item, index) in carModel.tableOptions" :key="(index+50)">
            <el-row>
              <el-col :span="6">
                <!--                <el-select v-model="tableType[index].tableOptionType" placeholder="请选择类型">-->
                <el-select v-model="carModel.tableOptions[index].valueType" placeholder="请选择类型">
                  <el-option
                    v-for="tot in tableOptionsType"
                    :key="tot.value"
                    :label="tot.label"
                    :value="tot.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <!--                v-for="(item, index) in carModel.tableOptions"-->
                <!--                :key="index"-->
                <el-input
                  v-model="carModel.tableOptions[index].name"
                  style="display:inline"
                  :placeholder="'名称'+(index+1)"
                />
              </el-col>
            </el-row>
            <div v-show="carModel.tableOptions.length>1&&dialogStatus==='create'" style="float:right">
              <el-button @click.prevent="removeTableOption()">删除</el-button>
            </div>
          </el-form-item>

          <!-- 检查项模板实例 -->
          <el-form-item style="margin-bottom:0px" label="检查项模板实例" prop="options.name" />
          <el-form-item v-for="(item, index) in groupItemNumber" :key="item">
            <!--            <el-form-item>-->
            <el-row>
              <el-col :span="6">
                <el-select v-model="carModel.options[index].type" placeholder="请选择类型" @change="resetOptionValue(index)">
                  <el-option
                    v-for="op in optionType"
                    :key="op.value"
                    :label="op.label"
                    :value="op.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-input v-model="carModel.options[index].group" style="display:inline" placeholder="分组名" />
              </el-col>
              <el-col :span="6">
                <el-input v-model="carModel.options[index].name" style="display:inline" placeholder="名称" />
              </el-col>
              <el-col :span="6">
                <el-input v-model="carModel.options[index].remarks" style="display:inline" placeholder="备注" />
              </el-col>
              <el-col
                v-for="(item2, index2) in carModel.options[index].optionValuePoList"
                :key="index2"
                :span="6"
              >
                <el-input v-model="carModel.options[index].optionValuePoList[index2]" :placeholder="'默认值'+(index2+1)" />
              </el-col>
            </el-row>
            <div v-show="dialogStatus==='create'" style="float:right">
              <div v-show="carModel.options[index].type===2" style="display:inline-block;">
                <el-button style="width:40px;height:30px;padding:0;" @click.prevent="addOptionValue(index)">+
                </el-button>
                <el-button style="width:40px;height:30px;padding:0;" @click.prevent="removeOptionValue(index)">-
                </el-button>
              </div>
              <el-button @click.prevent="removeOption(index)">删除</el-button>
            </div>
            <!--            </el-form-item>-->
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">提交</el-button>
          <el-button v-show="dialogStatus==='create'" icon="el-icon-circle-plus" @click="addTableOption">测试项</el-button>
          <el-button v-show="dialogStatus==='create'" icon="el-icon-circle-plus" @click="addOption">检查项</el-button>
          <el-button @click="resetCarModel">重置</el-button>
          <el-button @click="dialogFormVisible=false">取消</el-button>
        </div>
      </el-dialog>

      <el-tabs v-model="active" @tab-click="handleClick">

        <!-- 显示项目 -->
        <el-tab-pane label="模板信息">
          <el-table
            :key="tableKey"
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column label="编号" prop="id" sortable="custom" align="center" />
            <el-table-column label="项目名称" prop="name" align="center" />
            <el-table-column label="描述" prop="description" width="180px" align="center" />
            <el-table-column label="状态" prop="stateName" width="80px" align="center" />
            <el-table-column label="修改人图片" width="80px" align="center">
              <template slot-scope="{row}">
                <img :src="'http://'+row.updateUserImg" alt="无" width="60px" height="60px">
              </template>
            </el-table-column>

            <el-table-column label="类型" align="center">
              <template slot-scope="{row}">
                <span>{{ row.typeName || 'null' }}</span>
              </template>
            </el-table-column>

            <el-table-column label="创建时间" prop="createTime" align="center" />
            <el-table-column label="修改时间" prop="updateTime" align="center" />

            <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
              <template slot-scope="{row}">
                <el-button size="mini" @click="handleCheck(row)">
                  查看
                </el-button>
                <el-button type="primary" size="mini" @click="handleUpdate(row)">
                  编辑
                </el-button>
                <el-button type="danger" size="mini" @click="handleChangeState(row)">
                  禁用
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 底部分页组件 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>

        <!-- 查看模板详情 -->
        <el-tab-pane label="查看详情">
          <div class="dialog-view">
            <!--            <el-dialog v-if="dialogStatus=='check'" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">-->
            <el-form :model="carModel" style="max-height:600px;overflow-y:auto;">
              <el-form-item label="模板名" prop="name">
                <span>{{ carModel.name }}</span>
              </el-form-item>
              <el-form-item label="id" prop="id">
                <span>{{ carModel.id }}</span>
              </el-form-item>
              <el-form-item label="备注：" prop="description">
                <span>{{ carModel.description }}</span>
              </el-form-item>
              <el-form-item label="作者：" prop="createUserName">
                <span>{{ carModel.createUserName }}</span>
              </el-form-item>
              <el-form-item label="状态：" prop="stateName">
                <span>{{ carModel.stateName || 'null' }}</span>
              </el-form-item>
              <el-form-item label="类型：" prop="typeName">
                <span>{{ carModel.typeName || 'null' }}</span>
              </el-form-item>

              <el-form-item label="测试项：" prop="tableOptions"><br>
                <el-form-item style="text-indent:4em" label="类型：">
                  <span>{{ carModel.tableOptions.length>0?carModel.tableOptions[0].valueTypeName:'null' }}</span>
                </el-form-item>
                <el-form-item style="text-indent:4em" label="名称：">
                  <span
                    v-for="item of carModel.tableOptions"
                    :key="item.id"
                  >
                    {{ item.name }}
                  </span>
                </el-form-item>
              </el-form-item>

              <el-form-item label="检查项：" prop="options">
                <el-table
                  :data="carModel.options"
                  style="width: 100%"
                >
                  <el-table-column
                    prop="group"
                    label="组名"
                  />
                  <el-table-column
                    prop="name"
                    label="名称"
                  />
                  <el-table-column
                    prop="remarks"
                    label="备注"
                  />
                  <el-table-column
                    prop="typeName"
                    label="类型"
                  />
                  <el-table-column
                    prop="stateName"
                    label="状态"
                  />
                </el-table>
              </el-form-item>
            </el-form>

            <!--              <div slot="footer" class="dialog-footer">-->
            <!--                <el-button @click="dialogFormVisible = false">-->
            <!--                  关闭-->
            <!--                </el-button>-->
            <!--              </div>-->
            <!--            </el-dialog>-->
          </div>
        </el-tab-pane>

        <!--        修改/编辑项目-->
        <el-tab-pane label="编辑">
          <!--          <el-dialog-->
          <!--            v-if="dialogStatus!=='check'"-->
          <!--            :title="textMap[dialogStatus]"-->
          <!--            :visible.sync="dialogFormVisible"-->
          <!--            :close-on-click-modal="false"-->
          <!--          >-->
          <el-form :rules="carModelRules" :model="carModel" style="max-height:550px;overflow-y:auto;">
            <el-form-item label="模板名" prop="name">
              <el-input v-model="carModel.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="模板描述">
              <el-input
                v-model="carModel.description"
                type="textarea"
                :rows="3"
                placeholder="此处填写模板描述"
              />
            </el-form-item>

            <!-- 测试项模板实例 -->
            <el-form-item style="margin-bottom:0px" label="测试项模板实例" prop="tableOptions.name" />
            <el-form-item v-for="(item, index) in carModel.tableOptions" :key="(index+50)">
              <el-row>
                <el-col :span="6">
                  <!--                <el-select v-model="tableType[index].tableOptionType" placeholder="请选择类型">-->
                  <el-select v-model="carModel.tableOptions[index].valueType" placeholder="请选择类型">
                    <el-option
                      v-for="tot in tableOptionsType"
                      :key="tot.value"
                      :label="tot.label"
                      :value="tot.value"
                    />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <!--                v-for="(item, index) in carModel.tableOptions"-->
                  <!--                :key="index"-->
                  <el-input
                    v-model="carModel.tableOptions[index].name"
                    style="display:inline"
                    :placeholder="'名称'+(index+1)"
                  />
                </el-col>
              </el-row>
              <div v-show="carModel.tableOptions.length>1&&dialogStatus==='create'" style="float:right">
                <el-button @click.prevent="removeTableOption()">删除</el-button>
              </div>
            </el-form-item>
            <!-- 检查项模板实例 -->
            <el-form-item style="margin-bottom:0px" label="检查项模板实例" prop="options.name" />
            <el-form-item v-for="(item, index) in groupItemNumber" :key="item">
              <!--            <el-form-item>-->
              <el-row>
                <el-col :span="6">
                  <el-select v-model="carModel.options[index].type" placeholder="请选择类型" @change="resetOptionValue(index)">
                    <el-option
                      v-for="op in optionType"
                      :key="op.value"
                      :label="op.label"
                      :value="op.value"
                    />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-input v-model="carModel.options[index].group" style="display:inline" placeholder="分组名" />
                </el-col>
                <el-col :span="6">
                  <el-input v-model="carModel.options[index].name" style="display:inline" placeholder="名称" />
                </el-col>
                <el-col :span="6">
                  <el-input v-model="carModel.options[index].remarks" style="display:inline" placeholder="备注" />
                </el-col>
                <el-col
                  v-for="(item2, index2) in carModel.options[index].optionValuePoList"
                  :key="index2"
                  :span="6"
                >
                  <el-input v-model="carModel.options[index].optionValuePoList[index2]" :placeholder="'默认值'+(index2+1)" />
                </el-col>
              </el-row>
              <!--                <div v-show="dialogStatus==='create'" style="float:right">-->
              <!--                  <div v-show="carModel.options[index].type===2" style="display:inline-block;">-->
              <!--                    <el-button style="width:40px;height:30px;padding:0;" @click.prevent="addOptionValue(index)">+-->
              <!--                    </el-button>-->
              <!--                    <el-button style="width:40px;height:30px;padding:0;" @click.prevent="removeOptionValue(index)">- -->
              <!--                    </el-button>-->
              <!--                  </div>-->
              <!--                  <el-button @click.prevent="removeOption(index)">删除</el-button>-->
              <!--                </div>-->
              <!--            </el-form-item>-->
            </el-form-item>
          </el-form>
          <!--            <div slot="footer" class="dialog-footer">-->
          <el-button type="primary" @click="updateData()">提交</el-button>
          <!--              <el-button v-show="dialogStatus==='create'" icon="el-icon-circle-plus" @click="addTableOption">测试项</el-button>-->
          <!--              <el-button v-show="dialogStatus==='create'" icon="el-icon-circle-plus" @click="addOption">检查项</el-button>-->
          <el-button @click="resetCarModel">重置</el-button>
          <el-button @click="dialogFormVisible=false">取消</el-button>
          <!--            </div>-->
          <!--          </el-dialog>-->
        </el-tab-pane>

      </el-tabs>
    </div>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import { queryTemp, getDetail, createTemp, changeTempState, updateTemp } from '@/api/template'
  import { mapGetters } from 'vuex'

  export default {
    components: { Pagination },
    data() {
      return {
        dialogFormVisible: false,
        dialogStatus: '',
        active: 0,
        textMap: {
          // update: '修改模板',
          create: '添加模板',
          check: '模板详情'
        },
        // 搜索框请求数据及分页数据
        listQuery: {
          page: 1,
          pageSize: 10,
          type: '',
          name: '',
          state: 4
        },
        tableKey: 0,
        total: 0,
        list: [],
        itemIndex: 0,
        groupItemNumber: [],
        carModel: {
          id: '',
          name: '',
          description: '',
          state: '',
          type: 4,
          createUser: '',
          updateUser: '',
          createUserImg: '',
          updateUserImg: '',
          createTime: '',
          updateTime: '',
          stateName: '',
          typeName: '',
          createUserName: '',
          updateUserName: '',
          tableOptions: [{
            // id: '',
            name: '',
            // type: 10,
            // typeName: '',
            // state: 1,
            // stateName: '',
            valueType: 1
            // valueTypeName: ''
          }],
          options: [{
            id: '',
            group: '',
            name: '',
            type: 1,
            typeName: '',
            remarks: '',
            state: '',
            stateName: '',
            valueType: 1,
            optionValuePoList: ['']
          }]
        },

        carModelRules: {
          name: { required: true, trigger: 'blur' },
          'tableOptions.name': { required: true, trigger: 'blur' },
          'options.name': { required: true, trigger: 'blur' }
        },

        // tableType: [{
        //   tableOptionType: 1
        // }],
        // tableOptionType: 1,
        tableOptionsType: [
          { value: 1, label: '文本' },
          { value: 2, label: '数字' }
        ],
        optionType: [ // 子项类型
          { value: 1, label: '文本' },
          { value: 2, label: '单选' },
          { value: 3, label: '图片' },
          { value: 4, label: '日期' }
        ],

        listLoading: true
      }
    },
    created() {
      this.getList()
      this.groupItemNumber.push(this.itemIndex)
    },
    computed: {
      ...mapGetters([
        'img'
      ])
    },
    methods: {
      // 表格初始化
      getList() {
        this.listLoading = true
        queryTemp(this.listQuery).then(response => {
          if (response.resultCode === 200) {
            this.list = response.data.list
            this.total = response.data.count
          }
        })
        this.listLoading = false
      },

      // 标签页切换
      handleClick(tab, event) {
        console.log(tab, event)
      },

      // 打开创建模板按钮
      handleCreate() {
        this.resetCarModel()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      // 确认增加模板
      createData() {
        if (this.checkRequire()) {
          const model = {
            name: this.carModel.name,
            description: this.carModel.description,
            tableOptions: this.carModel.tableOptions,
            options: this.carModel.options
            // valueType: this.tableOptionType
          }
          createTemp(model).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        } else {
          this.$message.warning('请输入必填项')
        }
      },

      // 修改模板信息按钮
      handleUpdate(row) {
        // dialogFormVisible = false
        // this.dialogStatus = 'update'
        const num = 2
        this.active = num.toString()
        getDetail(row.id).then(response => {
          if (response.resultCode === 200) {
            this.resetCarModel()
            this.carModel = Object.assign(response.data)
            this.carModel.updateUserImg = this.img
            this.dialogFormVisible = false
            this.itemIndex = response.data.options.length - 1
            for (let index = 1; index <= this.itemIndex; index++) {
              this.groupItemNumber.push(index)
            }
          }
        })
      },
      // 确认修改模板信息
      updateData() {
        if (this.carModel.state == 2) {
          this.$message.warning('该模板正在使用，无法修改')
        } else {
          if (this.checkRequire()) {
            updateTemp(this.carModel).then(response => {
              if (response.status === 200 || response.resultCode === 200) {
                this.$notify({
                  title: 'Success',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList()
              }
            })
            this.dialogFormVisible = false
          } else {
            this.$message.warning('请输入必填项')
          }
        }
      },

      // 查看模板信息按钮
      handleCheck(row) {
        const num = 1
        this.active = num.toString()
        this.dialogStatus = 'check'
        getDetail(row.id, 1).then(response => {
          if (response.resultCode === 200) {
            this.resetCarModel()
            this.carModel = Object.assign(response.data)
            this.dialogFormVisible = true
            this.itemIndex = response.data.options.length - 1
            for (let index = 1; index <= this.itemIndex; index++) {
              this.groupItemNumber.push(index)
            }
          }
        })
      },

      // 增加表单项
      addTableOption() {
        this.carModel.tableOptions.push({ name: '', valueType: 1 })
      },
      // 删除表单项
      removeTableOption() {
        this.carModel.tableOptions.pop()
      },

      // 增加检查项
      addOption() {
        this.carModel.options.push({
          name: '',
          type: 1,
          remarks: '',
          group: '',
          valueType: 1,
          optionValuePoList: ['']
        })
        console.log(this.itemIndex)
        this.groupItemNumber.push(++this.itemIndex)
      },
      // 删除检查项
      removeOption(index) {
        if (this.groupItemNumber.length > 1) {
          this.carModel.options.splice(index, 1)
          this.groupItemNumber.splice(index, 1)
        } else {
          console.log('无法删除最后一项')
        }
      },

      // 禁用模板
      handleChangeState(row) {
        if (row.state == 1) {
          const data = {
            modelId: row.id,
            state: 3
          }
          changeTempState(data).then(res => {
            if (res.resultCode === 200) {
              this.$notify({
                title: '提示',
                message: '禁用成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        } else {
          this.$message.warning('该模板正在使用，无法禁用')
        }
      },

      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },

      // 创建模板的几个按钮
      // submitForm(formName) {
      //   this.$refs[formName].validate((valid) => {
      //     if (valid) {
      //       alert('submit!')
      //     } else {
      //       console.log('error submit!!')
      //       return false
      //     }
      //   })
      // },

      // 查找过滤器
      handleFilter() {
        this.getList()
      },

      // 增加默认值项
      addOptionValue(index) {
        this.carModel.options[index].optionValuePoList.push('')
      },
      // 减少默认值项
      removeOptionValue(index) {
        if (this.carModel.options[index].optionValuePoList.length > 1) {
          this.carModel.options[index].optionValuePoList.pop()
        }
      },

      // 当缺少必填项时无法提交
      checkRequire() {
        let result = true
        for (let i = 0; i < this.carModel.tableOptions.length; i++) {
          result = result && this.carModel.tableOptions[i].name != ''
          if (!result) {
            return result
          }
        }
        for (let i = 0; i < this.carModel.options.length; i++) {
          result = result && this.carModel.options[i].name != '' && this.carModel.options[i].group != ''
          if (!result) {
            return result
          }
          if (this.carModel.options[i].type == 2) {
            for (let j = 0; j < this.carModel.options[i].optionValuePoList.length; j++) {
              result = result && this.carModel.options[i].optionValuePoList[j] != ''
              if (!result) {
                return result
              }
            }
          }
        }
        return result
      },

      // 重置carModel中部分用于创建模板的数据项
      resetCarModel() {
        this.itemIndex = 0
        this.groupItemNumber = [this.itemIndex]
        this.carModel.name = ''
        this.carModel.description = ''
        this.carModel.tableOptions = [{
          name: '',
          valueType: 1
        }]
        this.carModel.options = [{
          name: '',
          type: 1,
          group: '',
          remarks: '',
          valueType: 1,
          optionValuePoList: ['']
        }]
      },

      // 重置optionValuePoList
      resetOptionValue(index) {
        this.carModel.options[index].optionValuePoList = ['']
      }

    }
  }
</script>

<style>
  .el-dialog__wrapper {
    min-width: 2000px;
  }

  .el-form-item__content {
    margin-right: 10%;
  }

  .el-radio {
    margin-top: 9px;
  }
</style>
